package cn.sinata.wanglin.village.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.xilada.xldutils.fragment.BaseLazyFragment;
import com.xilada.xldutils.utils.ActivityUtil;
import com.xilada.xldutils.utils.SharedPreferencesUtils;
import com.xilada.xldutils.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sinata.wanglin.MainActivity;
import cn.sinata.wanglin.MyApplication;
import cn.sinata.wanglin.R;
import cn.sinata.wanglin.SendToMeActivity;
import cn.sinata.wanglin.commonutils.Constant;
import cn.sinata.wanglin.commonutils.FragmentAdapter;
import cn.sinata.wanglin.model.WeatherInfo;
import cn.sinata.wanglin.utils.RxBus;
import cn.sinata.wanglin.village.activity.ChoiceVillageActivity;
import rx.Observable;
import rx.functions.Action1;

/**
 * description：
 * Created by kaihongwu on 2016/12/05 下午 12:00
 */
public class VillageFragment extends BaseLazyFragment {
    @BindView(R.id.iv_weatherimg)
    SimpleDraweeView iv_weatherimg;//天气图标
    @BindView(R.id.tv_weather)
    TextView tv_weather;//天气
    @BindView(R.id.tv_tips)
    TextView tv_tips;//
    @BindView(R.id.tv_title)
    TextView tv_title;//
    @BindView(R.id.viewpager)
    ViewPager viewpager;//
    @BindView(R.id.tabs)
    TabLayout tabs;//
    @BindView(R.id.fl_sendtome)
    FrameLayout fl_sendtome;//
    CelldynamicsFragment mCelldynamicsFragment;//小区生活
    CitygossipFragment mCitygossipFragment;//同城八卦
    NewsinformationFragment mNewsinformationFragment;//新闻资讯
    private FragmentAdapter adapter;
    private Observable<WeatherInfo> weatherOb;


    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_village;
    }

    @Override
    protected void onFirstVisibleToUser() {

        setupViewPager();
        registBroadcast();

        weatherOb = RxBus.get().register(MainActivity.REFRESH_WEATHER, WeatherInfo.class);
        weatherOb.subscribe(new Action1<WeatherInfo>() {
            @Override
            public void call(WeatherInfo weatherInfo) {
                String weatherStr = weatherInfo.getResults().get(0).getWeather_data().get(0).getTemperature();
                String weatherImg = weatherInfo.getResults().get(0).getWeather_data().get(0).getNightPictureUrl();
                if (!TextUtils.isEmpty(weatherStr)) {
                    tv_weather.setText(weatherStr);
                }
                if (!TextUtils.isEmpty(weatherImg)) {
                    iv_weatherimg.setImageURI(weatherImg);
                }
            }
        });


    }

    private void registBroadcast() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(Constant.BROADCAST_CHOICE_VILLAGE);
        myIntentFilter.addAction(Constant.BROADCAST_MSG_ME);
        getActivity().registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context,
                              Intent intent) {
            String action = intent.getAction();

            if (action.equals(Constant.BROADCAST_CHOICE_VILLAGE)) {
                showToast("选择了小区：" + MyApplication.houseName);
                showTitle(0);
                viewpager.setCurrentItem(0);
                mCelldynamicsFragment.setCurrentTab(0);
            } else if (action.equals(Constant.BROADCAST_MSG_ME)) {
                tv_tips.setVisibility(View.VISIBLE);
            }

        }
    };

    public void reRefresh(int type) {
        //吐槽1，八卦2，圈子3，活动4；
        switch (type) {
            case 1:
                if (mCelldynamicsFragment != null) {
                    viewpager.setCurrentItem(0);
                    adapter.notifyDataSetChanged();
                    mCelldynamicsFragment.setCurrentTab(0);

                }
                break;
            case 2:
                if (mCitygossipFragment != null) {
                    viewpager.setCurrentItem(1);
                    mCitygossipFragment.reFresh();
                }
                break;
            case 3:
                break;
            case 4:
                if (mCelldynamicsFragment != null) {
                    viewpager.setCurrentItem(0);
                    mCelldynamicsFragment.setCurrentTab(1);
                }
                break;
        }

    }

    @Override
    protected void onVisibleToUser() {

    }

    @Override
    protected void onInvisibleToUser() {

    }

    private void setupViewPager() {
        List<String> titles = new ArrayList<>();
        titles.add("小区动态");
        titles.add("同城八卦");
        titles.add("新闻资讯");
        List<Fragment> mFragments = new ArrayList<>();
        mCelldynamicsFragment = new CelldynamicsFragment();
        mCitygossipFragment = new CitygossipFragment();
        mNewsinformationFragment = new NewsinformationFragment();
        mFragments.add(mCelldynamicsFragment);
        mFragments.add(mCitygossipFragment);
        mFragments.add(mNewsinformationFragment);
        adapter = new FragmentAdapter(getChildFragmentManager(), mFragments, titles);
        viewpager.setOffscreenPageLimit(3);
        viewpager.setAdapter(adapter);
        tabs.setupWithViewPager(viewpager);
        //判断用户绑定小区没,没绑定就显示同城八卦，绑定了就显示小区动态
        String housid = SharedPreferencesUtils.getString(Constant.SP_HOUSING_ID);
        String houseName = SharedPreferencesUtils.getString(Constant.SP_HOUSING_NAME);
        if (!TextUtils.isEmpty(housid) && !"-1".equals(housid)) {
            Utils.systemErr("---housid--" + housid);
            MyApplication.houseid = housid;
            MyApplication.houseName = houseName;
            viewpager.setCurrentItem(0);
        } else {
            MyApplication.houseid = null;
            MyApplication.houseName = null;
            viewpager.setCurrentItem(1);
        }
        viewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {

                switch (position) {
                    case 0:
                        if (TextUtils.isEmpty(MyApplication.houseid) || "-1".equals(MyApplication.houseid)) {
                            showToast("请先选择小区");
                            viewpager.setCurrentItem(1);
                            showTitle(1);
                            ActivityUtil.create(VillageFragment.this).go(ChoiceVillageActivity.class)
                                    .start();
                        } else {
                            showTitle(0);
                        }

                        break;
                    default:
                        showTitle(position);
                        break;

                }


            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        showTitle(viewpager.getCurrentItem());

    }

    private void showTitle(int position) {

        Drawable img_off = ContextCompat.getDrawable(context,R.mipmap.ic_down_logo);
        String city = MyApplication.city;
        String showtitle = city.substring(0, city.length() - 1);
        switch (position) {
            case 0:
                if (!TextUtils.isEmpty(MyApplication.houseName)) {
                    tv_title.setText(MyApplication.houseName);
                } else {
                    tv_title.setText("选择小区");
                }
                // 调用setCompoundDrawables时，必须调用Drawable.setBounds()方法,否则图片不显示
                img_off.setBounds(0, 0, img_off.getMinimumWidth(), img_off.getMinimumHeight());
                tv_title.setCompoundDrawables(null, null, img_off, null); //设置右图标
                break;
            case 1:

                tv_title.setText(showtitle);
                tv_title.setCompoundDrawables(null, null, null, null); //设置右图标
                break;
            case 2:
                tv_title.setText(showtitle);
                tv_title.setCompoundDrawables(null, null, null, null); //设置右图标
                break;
        }

    }

    @OnClick({R.id.fl_sendtome, R.id.tv_title})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.fl_sendtome:
                //描述:@我
                tv_tips.setVisibility(View.GONE);
                ActivityUtil.create(VillageFragment.this).go(SendToMeActivity.class)
                        .start();
                break;
            case R.id.tv_title:
                //描述:选择小区
                if (viewpager.getCurrentItem() == 0) {
                    ActivityUtil.create(VillageFragment.this).go(ChoiceVillageActivity.class)
                            .start();
                }
                break;

        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mBroadcastReceiver != null) {
            getActivity().unregisterReceiver(mBroadcastReceiver);
        }
        if (weatherOb != null) {
            RxBus.get().unregister(MainActivity.REFRESH_WEATHER, weatherOb);
        }
    }
}
